<template>
  <div class="customer-container base-page-container">
    <!-- 搜索区域 -->
    <common-search
      v-model="searchForm"
      :search-items="searchItemsConfig"
      @search="handleSearch"
      @reset="fetchTableData"
    >
      <!-- 自定义插槽示例 -->
      <template #customSlot="{ form }">
        <!-- 这里可以放置自定义搜索组件 -->
        <el-select v-model="form.customField" placeholder="自定义字段" style="width: 230px">
          <el-option label="选项1" value="1" />
          <el-option label="选项2" value="2" />
        </el-select>
      </template>
    </common-search>
    
    <!-- 操作按钮区域 -->
    <action-buttons
      :buttons="buttonsConfig"
	  :selected-data="selectedRows"
      @add="handleAdd"
      @export="handleExport"
      @import="handleImport"
      @enable="handleEnable"
      @disable="handleDisable"
    />
    
    <!-- 表格区域 -->
    <custom-table
      :data="tableData"
      :columns="tableColumns"
      :loading="tableLoading"
      :current-page="pagination.currentPage"
      :page-size="pagination.pageSize"
      :total="pagination.total"
      table-id="customer-table"
      @selection-change="handleSelectionChange"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    >
      <!-- 状态列的自定义插槽 -->
      <template #status="{ row }">
        <el-tag :type="row.status === '启用' ? 'success' : 'info'">
          {{ row.status }}
        </el-tag>
      </template>
      
      <!-- 操作列 -->
      <template #operation="{ row }">
        <theme-button v-if="tablePermissions.edit" link @click="handleEdit(row)">编辑</theme-button>
        <theme-button v-if="tablePermissions.view" link @click="handleView(row)">查看</theme-button>
        <theme-button v-if="tablePermissions.log" link @click="handleLog(row)">日志</theme-button>
      </template>
    </custom-table>
    
    <!-- 客户信息弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="750px" destroy-on-close class="base-dialog"
      :close-on-click-modal="false">
      <el-form ref="customerFormRef" :model="customerForm" :rules="customerFormRules" label-width="80px"
        class="base-form">
        <div class="form-row">
          <el-form-item label="客户编号" prop="code">
            <el-input v-model="customerForm.code" placeholder="请输入客户编号"></el-input>
          </el-form-item>
          <el-form-item label="客户名称" prop="name">
            <el-input v-model="customerForm.name" placeholder="请输入客户名称"></el-input>
          </el-form-item>
        </div>
        
        <div class="form-row">
          <el-form-item label="客户等级" prop="level">
            <el-select v-model="customerForm.level" placeholder="请选择客户等级" style="width: 100%">
              <el-option label="请选择客户等级" value=""></el-option>
              <el-option label="一级客户" value="一级客户"></el-option>
              <el-option label="二级客户" value="二级客户"></el-option>
              <el-option label="三级客户" value="三级客户"></el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="客户标签" prop="tag">
            <el-select v-model="customerForm.tag" placeholder="请选择客户标签" style="width: 100%">
              <el-option label="请选择客户标签" value=""></el-option>
              <el-option label="优质客户" value="优质客户"></el-option>
              <el-option label="一般客户" value="一般客户"></el-option>
              <el-option label="重点客户" value="重点客户"></el-option>
            </el-select>
          </el-form-item> -->
        </div>
        
        <div class="form-row" style="border-bottom: solid 1px #eee;">
          <el-form-item label="货主" prop="owner">
            <el-select v-model="customerForm.owner" placeholder="请选择货主" style="width: 50%">
              <el-option label="请选择货主" value=""></el-option>
              <el-option label="货主A" value="货主A"></el-option>
              <el-option label="货主B" value="货主B"></el-option>
              <el-option label="货主C" value="货主C"></el-option>
            </el-select>
          </el-form-item>
        </div>
        
        <div class="form-row full-width">
          <el-form-item label="客户地址" prop="region">
            <region-cascader v-model="customerForm.region" placeholder="请选择所在区域" :level="3" :separator="'/'"
            	style="width: 100%" filterable clearable :use-code-data="false" :return-code="false" />
          </el-form-item>
        </div>
		
		<div class="form-row full-width">
		  <el-form-item label="详细地址" prop="address" class="full-width-item">
		    <el-input v-model="customerForm.address" placeholder="请输入详细地址" type="textarea" rows="3"></el-input>
		  </el-form-item>
		</div>
        
        <div class="form-row">
          <el-form-item label="邮编" prop="zipCode">
            <el-input v-model="customerForm.zipCode" placeholder="请输入邮编"></el-input>
          </el-form-item>
          <el-form-item label="联系人" prop="contactPerson">
            <el-input v-model="customerForm.contactPerson" placeholder="请输入联系人"></el-input>
          </el-form-item>
        </div>
        
        <div class="form-row">
          <el-form-item label="手机号" prop="contactPhone">
            <el-input v-model="customerForm.contactPhone" placeholder="请输入手机号"></el-input>
          </el-form-item>
          <el-form-item label="固话" prop="telephone">
            <el-input v-model="customerForm.telephone" placeholder="请输入固话"></el-input>
          </el-form-item>
        </div>
        
        <div class="form-row full-width">
          <el-form-item label="备注" prop="remark" class="full-width-item">
            <el-input v-model="customerForm.remark" placeholder="请输入备注" type="textarea" rows="3"></el-input>
          </el-form-item>
        </div>
      </el-form>
      <template #footer>
        <dialog-footer 
          cancel-text="取消"
          confirm-text="确定"
          @cancel="dialogVisible = false" 
          @confirm="submitForm" 
        />
      </template>
    </el-dialog>
    
    <!-- 日志弹窗 -->
    <log-dialog
      v-model:visible="logDialogVisible"
      :log-data="logData"
      :total="logPagination.total"
      :current-page="logPagination.currentPage"
      :page-size="logPagination.pageSize"
      @size-change="handleLogSizeChange"
      @current-change="handleLogCurrentChange"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useTheme } from '@/hooks/useTheme'
import { RegionCascader } from '@/components/common'

// 使用主题组合API
const { themeType } = useTheme()

// 判断是否开发环境
const isDevelopment = computed(() => {
  return import.meta.env.MODE === 'development'
})

// 搜索项配置列表
const searchItemsConfig = [
  {
    label: '客户编号',
    prop: 'code',
    type: 'el-input',
    placeholder: '请输入客户编号',
    defaultVisible: true
  },
  {
    label: '客户名称',
    prop: 'name',
    type: 'el-input',
    placeholder: '请输入客户名称',
    defaultVisible: true
  },
  {
    label: '状态',
    prop: 'status',
    type: 'el-select',
    placeholder: '请选择状态',
    defaultVisible: true,
    options: [
      { label: '请选择状态', value: '' },
      { label: '启用', value: '启用' },
      { label: '停用', value: '停用' }
    ]
  },
  {
    label: '货主',
    prop: 'owner',
    type: 'el-select',
    placeholder: '请选择货主',
    defaultVisible: true,
    multiple: true,
    collapseTags: true,
    collapseTagsTooltip: true,
    options: [
      { label: '货主A', value: '货主A' },
      { label: '货主B', value: '货主B' },
      { label: '货主C', value: '货主C' }
    ]
  },
  // {
  //   label: '创建日期',
  //   prop: 'createDate',
  //   type: 'el-date-picker',
  //   placeholder: '请选择创建日期',
  //   defaultVisible: false,
  //   dateType: 'date',
  //   format: 'YYYY-MM-DD',
  //   valueFormat: 'YYYY-MM-DD'
  // },
  // {
  //   label: '联系人',
  //   prop: 'contactPerson',
  //   type: 'el-input',
  //   placeholder: '请输入联系人',
  //   defaultVisible: false
  // },
  // {
  //   label: '联系电话',
  //   prop: 'contactPhone',
  //   type: 'el-input',
  //   placeholder: '请输入联系电话',
  //   defaultVisible: false
  // },
  // {
  //   label: '日期范围',
  //   prop: 'dateRange',
  //   type: 'el-date-picker',
  //   placeholder: '请选择日期范围',
  //   defaultVisible: false,
  //   dateType: 'daterange',
  //   format: 'YYYY-MM-DD',
  //   valueFormat: 'YYYY-MM-DD',
  //   startPlaceholder: '开始日期',
  //   endPlaceholder: '结束日期',
  //   rangeKeys: ['startDate', 'endDate']
  // }
]

// 操作按钮配置
const buttonsConfig = ref({
  add: { visible: true, order: 1, type: 'success' },
  enable: { visible: true, order: 2 },
  disable: { visible: true, order: 3 },
  delete: { visible: false, order: 4, type: 'danger' },
  import: { visible: false, order: 5 },
  export: { visible: false, order: 6 },
  viewLog: { visible: false, order: 7 },
  edit: { visible: false, order: 8 }
})

// 表格操作权限
const tablePermissions = ref({
  edit: true,
  view: true,
  log: true
})

// 搜索表单数据
const searchForm = reactive({
  code: '',
  name: '',
  status: '',
  createDate: '',
  owner: '',
  contactPerson: '',
  contactPhone: '',
  dateRange: []
})

// 表格数据相关
const tableData = ref([])
const tableLoading = ref(false)
const selectedRows = ref([])

// 分页相关
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 客户表单相关
const customerFormRef = ref(null)
const dialogVisible = ref(false)
const dialogType = ref('add') // 'add' 或 'edit'
const customerForm = reactive({
  id: '',
  code: '',
  name: '',
  level: '',
  tag: '',
  owner: '',
  region: '',
  address: '',
  zipCode: '',
  contactPerson: '',
  contactPhone: '',
  telephone: '',
  remark: ''
})

// 表单校验规则
const customerFormRules = {
  code: [
    { required: true, message: '请输入客户编号', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入客户名称', trigger: 'blur' }
  ],
  owner: [
    { required: true, message: '请选择货主', trigger: 'change' }
  ],
  contactPerson: [
    { required: true, message: '请输入联系人', trigger: 'blur' }
  ],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' }
  ]
}

// 日志弹窗相关
const logDialogVisible = ref(false)
const logData = ref([])
const logPagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 添加计算属性获取对话框标题
const dialogTitle = computed(() => {
  return dialogType.value === 'add' ? '新增客户信息' : '编辑客户信息'
})

// 表格列配置
const tableColumns = ref([
  { prop: 'code', label: '客户编码', width: '120', minWidth: '120', visible: true },
  { prop: 'name', label: '客户名称', width: '120', minWidth: '120', visible: true },
  { prop: 'owner', label: '货主', width: '100', minWidth: '100', visible: true },
  { prop: 'status', label: '状态', width: '80', minWidth: '80', visible: true },
  { prop: 'contactPerson', label: '联系人', width: '100', minWidth: '100', visible: true },
  { prop: 'contactPhone', label: '手机号', width: '120', minWidth: '120', visible: true },
  { prop: 'contactAddress', label: '联系地址', minWidth: '200', visible: true },
  { prop: 'remark', label: '备注', width: '150', minWidth: '150', visible: true },
  { prop: 'operation', label: '操作', width: '160', minWidth: '160', fixed: 'right', visible: true }
])

// 计算表格高度
const tableHeight = computed(() => {
  // 考虑页面其他元素高度，加大减去的值以确保有足够的空间
  // 大约 180px 为搜索区域和操作按钮的高度，70px 为分页器和边距
  return window.innerHeight - 250;
})

// 获取表格数据
const fetchTableData = async () => {
  tableLoading.value = true
  
  try {
    // 模拟异步请求
    if (isDevelopment.value) {
      setTimeout(() => {
        // 模拟数据
        tableData.value = [
          {
            id: '1',
            code: 'KH11011',
            name: '客户A',
            owner: '货主A',
            status: '启用',
            contactPerson: '王阳明',
            contactPhone: '13587584785',
            contactAddress: '浙江省杭州市西湖区西溪大道XX路',
            remark: ''
          },
          {
            id: '2',
            code: 'KH11011',
            name: '客户A',
            owner: '货主A',
            status: '启用',
            contactPerson: '王阳明',
            contactPhone: '13587584785',
            contactAddress: '浙江省杭州市西湖区西溪大道XX路',
            remark: ''
          }
        ]
        
        pagination.total = 50 // 模拟总数据量
        tableLoading.value = false
      }, 500)
    } else {
      // 实际环境 API 调用
      // const res = await fetchCustomerList({
      //   pageNum: pagination.currentPage,
      //   pageSize: pagination.pageSize,
      //   ...searchForm
      // })
      // tableData.value = res.data
      // pagination.total = res.total
      tableLoading.value = false
    }
  } catch (error) {
    console.error('获取客户列表失败：', error)
    tableLoading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  pagination.currentPage = 1
  fetchTableData()
}

// 处理表格选择
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}

// 处理分页大小变化
const handleSizeChange = (size) => {
  pagination.pageSize = size
  fetchTableData()
}

// 处理页码变化
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  fetchTableData()
}

// 处理新增客户
const handleAdd = () => {
  dialogType.value = 'add'
  dialogVisible.value = true
  // 重置表单
  Object.keys(customerForm).forEach(key => {
    customerForm[key] = ''
  })
}

// 处理编辑客户
const handleEdit = (row) => {
  dialogType.value = 'edit'
  dialogVisible.value = true
  
  // 填充表单数据
  Object.keys(customerForm).forEach(key => {
    customerForm[key] = row[key] || ''
  })
}

// 处理查看客户
const handleView = (row) => {
  // 实现查看逻辑
  console.log('查看客户：', row)
}

// 处理日志
const handleLog = (row) => {
  logDialogVisible.value = true
  
  // 模拟获取日志数据
  setTimeout(() => {
    logData.value = [
      {
        operateTime: '2024-03-18 15:30:45',
        operator: '管理员',
        operateContent: '新增客户信息'
      },
      {
        operateTime: '2024-03-19 09:15:22',
        operator: '管理员',
        operateContent: '修改客户信息'
      }
    ]
    logPagination.total = 2
  }, 300)
}

// 处理日志分页
const handleLogSizeChange = (size) => {
  logPagination.pageSize = size
  // 重新获取日志数据
}

const handleLogCurrentChange = (page) => {
  logPagination.currentPage = page
  // 重新获取日志数据
}

// 处理导出
const handleExport = () => {
  console.log('导出客户数据')
  // 实现导出逻辑
}

// 处理导入
const handleImport = () => {
  console.log('导入客户数据')
  // 实现导入逻辑
}

// 处理启用
const handleEnable = () => {
  if (selectedRows.value.length === 0) {
    // 提示用户选择数据
    ElMessage.warning('请先选择需要启用的客户')
    return
  }
  
  console.log('启用选中的客户')
  // 实现启用逻辑
}

// 处理停用
const handleDisable = () => {
  if (selectedRows.value.length === 0) {
    // 提示用户选择数据
    ElMessage.warning('请先选择需要停用的客户')
    return
  }
  
  console.log('停用选中的客户')
  // 实现停用逻辑
}

// 提交表单
const submitForm = async () => {
  if (!customerFormRef.value) return
  
  customerFormRef.value.validate(async (valid) => {
    if (valid) {
      console.log('表单数据：', customerForm)
      
      // 模拟提交
      setTimeout(() => {
        ElMessage.success(dialogType.value === 'add' ? '新增客户成功' : '编辑客户成功')
        dialogVisible.value = false
        fetchTableData() // 刷新表格数据
      }, 500)
    } else {
      return false
    }
  })
}

// 页面加载时获取表格数据
onMounted(() => {
  fetchTableData()
})
</script>

<style lang="scss" scoped>
/* 使用全局样式类，保留特殊样式覆盖 */
</style> 